package com.gulimall.product.controller;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gulimall.common.enums.AttrEnum;
import com.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.gulimall.product.entity.AttrGroupEntity;
import com.gulimall.product.service.AttrAttrgroupRelationService;
import com.gulimall.product.service.AttrGroupService;
import com.gulimall.product.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gulimall.product.entity.AttrEntity;
import com.gulimall.product.service.AttrService;
import com.gulimall.common.utils.R;


/**
 * 商品属性
 *
 * @author ht
 * @email ht035200@163.com
 * @date 2020-04-08 11:13:29
 */
@RestController
@RequestMapping("product/attr")
public class AttrController {
    @Autowired
    private AttrService attrService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(AttrEntity attrEntity, @RequestParam(name = "page", defaultValue = "1") Integer pageNo, @RequestParam(name = "limit", defaultValue = "10") Integer pageSize, @RequestParam(name = "key") String key) {
        return R.ok().put("page", attrService.queryPage(new Page<>(pageNo, pageSize), attrEntity, key));
    }

    /**
     * 列表
     */
    @RequestMapping("/{type}/list/{catelogId}")
    public R baseList(@PathVariable("type") String type, @PathVariable("catelogId") Long catelogId, AttrEntity attrEntity, @RequestParam(name = "page", defaultValue = "1") Integer pageNo,
                      @RequestParam(name = "limit", defaultValue = "10") Integer pageSize, @RequestParam(name = "key", required = false) String key) {
        IPage<AttrEntity> iPage = attrService.queryPageByCateId(new Page<>(pageNo, pageSize), attrEntity, catelogId, key, type);
        List<AttrEntity> attrEntityList = iPage.getRecords();
        for (AttrEntity attr : attrEntityList) {
            attr.setCatelogIdsAndNames(categoryService.listWithTreeByCatId(attr.getCatelogId()));
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().select(AttrAttrgroupRelationEntity::getAttrGroupId).eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
            if (relationEntities.size() > 0) {
                LambdaQueryWrapper<AttrGroupEntity> queryWrapper = new LambdaQueryWrapper<AttrGroupEntity>().select(AttrGroupEntity::getAttrGroupName).eq(AttrGroupEntity::getCatelogId, attr.getCatelogId());
                if (AttrEnum.ATTR_TYPE_BASE.getType().equals(type)) {
                    queryWrapper.eq(AttrGroupEntity::getAttrGroupId, relationEntities.get(0).getAttrGroupId());
                    List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(queryWrapper);
                    if (attrGroupEntities.size() > 0) {
                        attr.setAttrGroupName(attrGroupEntities.get(0).getAttrGroupName());
                    }
                }
            }
        }
        return R.ok().put("page", iPage);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{attrId}")
    public R info(@PathVariable("attrId") Long attrId) {
        AttrEntity attr = attrService.getById(attrId);
        attr.setCatelogIdsAndNames(categoryService.listWithTreeByCatId(attr.getCatelogId()));
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().select(AttrAttrgroupRelationEntity::getAttrGroupId).eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId());
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationService.list(queryWrapper);
        if (attrgroupRelationEntities.size() > 0) {
            attr.setAttrGroupId(attrgroupRelationEntities.get(0).getAttrGroupId());
        }
        return R.ok().put("attr", attr).put("attrGroup", attrGroupService.list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, attr.getCatelogId())));
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody AttrEntity attr) {
        attrService.save(attr);
        if (null != attr.getAttrGroupId() && AttrEnum.ATTR_TYPE_BASE.getCode() != attr.getAttrType()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrId(attr.getAttrId());
            attrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelation);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public R update(@RequestBody AttrEntity attr) {
        attrService.updateById(attr);
        attrAttrgroupRelationService.remove(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
        AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelation.setAttrId(attr.getAttrId());
        attrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationService.save(attrAttrgroupRelation);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@RequestBody Long[] attrIds) {
        List<Long> ids = Arrays.asList(attrIds);
        attrService.removeByIds(ids);
        for (Long id : ids) {
            attrAttrgroupRelationService.remove(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, id));
        }
        return R.ok();
    }

}
